from threading import Lock


class BytesArray:
    def __init__(self, max_len=65535):
        self.ArrayBytes = bytes()
        self.index = 0
        self.max = max_len
        self.lock = Lock()

    def append(self, bytes_item):
        self.lock.acquire()
        self.ArrayBytes += bytes_item
        if self.index > self.max:
            self.ArrayBytes = self.ArrayBytes[self.index:]
            self.index = 0
        self.lock.release()

    def read(self, size):
        bytes_item = bytes()
        while len(bytes_item) < size:
            self.lock.acquire()
            read_len = size - len(bytes_item) + self.index
            read_bytes = self.ArrayBytes[self.index:read_len]
            bytes_item += read_bytes
            self.index += len(read_bytes)
            self.lock.release()
        return bytes_item

